/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.property.subinfo.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.property.buildinfo.entity.PropertyBuildinginfo;
import com.jeeplus.modules.property.buildinfo.service.PropertyBuildinginfoService;
import com.jeeplus.modules.property.subinfo.entity.PropertyHouseinfo;
import com.jeeplus.modules.property.subinfo.service.PropertyHouseinfoService;
import com.jeeplus.modules.property.vilageinfo.entity.PropertyVillageinfo;
import com.jeeplus.modules.property.vilageinfo.service.PropertyVillageinfoService;
import com.jeeplus.modules.sys.entity.DictValue;
import com.jeeplus.modules.sys.entity.Office;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 房屋信息Controller
 * @author 陈龙
 * @version 2019-01-08
 */
@Controller
@RequestMapping(value = "${adminPath}/property/houseinfo/propertyHouseinfo")
public class PropertyHouseinfoController extends BaseController {

	@Autowired
	private PropertyHouseinfoService propertyHouseinfoService;
	@Autowired
	private PropertyVillageinfoService propertyVillageinfoService;
	@Autowired
	private PropertyBuildinginfoService propertyBuildinginfoService;
	@ModelAttribute
	public PropertyHouseinfo get(@RequestParam(required=false) String id) {
		PropertyHouseinfo entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = propertyHouseinfoService.get(id);
		}
		if (entity == null){
			entity = new PropertyHouseinfo();
		}
		return entity;
	}
	
	/**
	 * 房屋信息列表页面
	 */
	@RequiresPermissions("property:houseinfo:propertyHouseinfo:list")
	@RequestMapping(value = {"list/{mode}", "/{mode}"})
	public String list(@PathVariable String mode,PropertyHouseinfo propertyHouseinfo, Model model) {
		model.addAttribute("propertyHouseinfo", propertyHouseinfo);
		List<PropertyVillageinfo> villList=propertyVillageinfoService.findList(new PropertyVillageinfo());
		List<DictValue> dvlist=new ArrayList<DictValue>();
		for(PropertyVillageinfo vinfo:villList){
			DictValue dv=new DictValue();
			dv.setLabel(vinfo.getVillname());
			dv.setValue(vinfo.getId());
			dvlist.add(dv);
		}
		model.addAttribute("dvlist", dvlist);
		if(mode!=null&&mode.equals("index")){
			return "modules/property/houseinfo/propertyHouseinfoListIndex";
		}
		return "modules/property/houseinfo/propertyHouseinfoList";
	}
	
		/**
	 * 房屋信息列表数据
	 */
	@ResponseBody
	@RequiresPermissions("property:houseinfo:propertyHouseinfo:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(PropertyHouseinfo propertyHouseinfo, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<PropertyHouseinfo> page = propertyHouseinfoService.findPage(new Page<PropertyHouseinfo>(request, response), propertyHouseinfo); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑房屋信息表单页面
	 */
	@RequiresPermissions(value={"property:houseinfo:propertyHouseinfo:view","property:houseinfo:propertyHouseinfo:add","property:houseinfo:propertyHouseinfo:edit"},logical=Logical.OR)
	@RequestMapping(value = "form/{mode}")
	public String form(@PathVariable  String mode, PropertyHouseinfo propertyHouseinfo, Model model) {
		model.addAttribute("propertyHouseinfo", propertyHouseinfo);
		model.addAttribute("mode", mode);

		return "modules/property/houseinfo/propertyHouseinfoForm";
	}

	/**
	 * 保存房屋信息
	 */
	@ResponseBody
	@RequiresPermissions(value={"property:houseinfo:propertyHouseinfo:add","property:houseinfo:propertyHouseinfo:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(PropertyHouseinfo propertyHouseinfo, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(propertyHouseinfo);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		propertyHouseinfoService.save(propertyHouseinfo);//保存
		j.setSuccess(true);
		j.setMsg("保存房屋信息成功");
		return j;
	}
	
	/**
	 * 删除房屋信息
	 */
	@ResponseBody
	@RequiresPermissions("property:houseinfo:propertyHouseinfo:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(PropertyHouseinfo propertyHouseinfo) {
		AjaxJson j = new AjaxJson();
		propertyHouseinfoService.delete(propertyHouseinfo);
		j.setMsg("删除房屋信息成功");
		return j;
	}
	
	/**
	 * 批量删除房屋信息
	 */
	@ResponseBody
	@RequiresPermissions("property:houseinfo:propertyHouseinfo:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			propertyHouseinfoService.delete(propertyHouseinfoService.get(id));
		}
		j.setMsg("删除房屋信息成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("property:houseinfo:propertyHouseinfo:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(PropertyHouseinfo propertyHouseinfo, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "房屋信息"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<PropertyHouseinfo> page = propertyHouseinfoService.findPage(new Page<PropertyHouseinfo>(request, response, -1), propertyHouseinfo);
    		new ExportExcel("房屋信息", PropertyHouseinfo.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出房屋信息记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@ResponseBody
	@RequiresPermissions("property:houseinfo:propertyHouseinfo:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<PropertyHouseinfo> list = ei.getDataList(PropertyHouseinfo.class);
			for (PropertyHouseinfo propertyHouseinfo : list){
				try{
					propertyHouseinfoService.save(propertyHouseinfo);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条房屋信息记录。");
			}
			j.setMsg( "已成功导入 "+successNum+" 条房屋信息记录"+failureMsg);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入房屋信息失败！失败信息："+e.getMessage());
		}
		return j;
    }
	
	/**
	 * 下载导入房屋信息数据模板
	 */
	@ResponseBody
	@RequiresPermissions("property:houseinfo:propertyHouseinfo:import")
    @RequestMapping(value = "import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "房屋信息数据导入模板.xlsx";
    		List<PropertyHouseinfo> list = Lists.newArrayList(); 
    		new ExportExcel("房屋信息数据", PropertyHouseinfo.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
    }
	/**
	 * 获取楼宇信息下拉框
	 */
	@ResponseBody
	@RequestMapping(value = "getBuildinginfo")
	public AjaxJson getBuildinginfo(String id) {
		AjaxJson j = new AjaxJson();
		LinkedHashMap<String,Object> map=new LinkedHashMap<String,Object>();
		PropertyBuildinginfo info=new PropertyBuildinginfo();
		Office villageinfo=new Office();
		villageinfo.setCode(id);
		info.setVillage(villageinfo);//传值的查询小区id
		List<PropertyBuildinginfo> villList=propertyBuildinginfoService.findList(info);
		List<DictValue> dvlist=new ArrayList<DictValue>();
		for(PropertyBuildinginfo vinfo:villList){//遍历构造字典下拉框
			DictValue dv=new DictValue();
			dv.setLabel(vinfo.getBuildingname());
			dv.setValue(vinfo.getId());
			dvlist.add(dv);
		}
		map.put("mapdata",dvlist);
		j.setBody(map);
		return j;
	}
	/**
	 * 房屋及车位信息列表页面
	 */
	//@RequiresPermissions("ipmp:houseinfo:ipmpHouseinfo:list")
	@RequestMapping(value = {"tab"})
	public String tab(String buildingid, Model model) {
		model.addAttribute("buildingid",buildingid);
		return "modules/property/houseinfo/tabList";
	}
}